<template>
  <basic-container>
    <div class="container-body">
      <el-form :inline="true" :model="query" class="demo-form-inline">
        <el-form-item label="年度:">
          <el-date-picker v-model="query.year" type="year" placeholder="选择年" value-format="yyyy">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="评分人:">
          <el-input size="medium" v-model="query.markUserName" placeholder="评分人"></el-input>
        </el-form-item>
        <el-form-item label="状态:">
          <el-select size="medium" v-model="query.status" placeholder="请选择" clearable>
            <el-option label="待评分" value="1"></el-option>
            <el-option label="已评分" value="2"></el-option>
            <el-option label="已结束" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="medium" type="primary" icon="el-icon-search" @click="onSearch" :loading="loading">搜索
          </el-button>
          <el-button size="medium" icon="el-icon-delete" @click="searchReset" :loading="loading">清空</el-button>
        </el-form-item>
      </el-form>
      <div class="scoreTotal">已评分<span>{{scoreTotal.scoreTotal}}</span>人，未评分<span>{{scoreTotal.activeTotal}}</span>人，共<span>{{scoreTotal.total}}</span>人</div>
      <el-table header-row-class-name="container-table-header"
                :data="data" size="medium"
                style="width: 100%;margin-bottom: 20px;"
                row-key="id"
                v-loading="loading">
        <el-table-column prop="examineYear" label="年度" width="80">
        </el-table-column>
        <el-table-column prop="projectName" label="考评项目">
        </el-table-column>
        <el-table-column prop="kpiType" label="考评类别">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.kpi_type" :value="scope.row.kpiType"/>
          </template>
        </el-table-column>
        <el-table-column prop="ownUserName" label="姓名">
        </el-table-column>
        <el-table-column prop="ownDeptName" label="单位">
        </el-table-column>
        <!--        <el-table-column prop="examineName" label="考评内容" min-width="100">
                </el-table-column>-->
<!--        <el-table-column prop="startTime" label="开始时间">
        </el-table-column>
        <el-table-column prop="endTime" label="结束日期">
        </el-table-column>-->
        <el-table-column prop="markUserName" label="评分人">
        </el-table-column>
        <el-table-column prop="score" label="评分" width="50">
          <template slot-scope="scope">
            <div>{{ scope.row.score > 0 ? scope.row.score : scope.row.status > 0 ? 0: '--'}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <div>{{ scope.row.status | scorePersonStatus }}</div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作" width="170">
          <template slot-scope="scope">
            <el-button v-if="permissions.scorePerson_get"
            type="text" size="medium" icon="el-icon-view" @click="showViewBox(scope.row)">查看
            </el-button>
            <el-button v-if="permissions.scorePerson_add && scope.row.status !== 3"
                       type="text" size="medium" icon="el-icon-edit" @click="showEditBox(scope.row)">考评
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="container-page">
        <el-pagination background
                       @size-change="sizeChange"
                       @current-change="currentChange"
                       :current-page="page.current"
                       :page-sizes="[10, 20, 30, 40, 50, 100]"
                       :page-size="10"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="page.total">
        </el-pagination>
      </div>
    </div>

    <el-dialog :visible.sync="formBox" :close-on-click-modal="!formBox" fullscreen
               :append-to-body="true" :before-close="resetForm" width="1000px" top="5vh">
      <div slot="title">
        <span style="font-size: 20px;margin-right: 20px;">{{formTitle}}</span>
        <el-button @click="resetForm" size="small" type="success" plain>返回</el-button>
      </div>
      <el-form ref="optForm" :model="form" label-width="120px">
        <el-row :gutter="24">
          <el-col :span = "6">
            <div><span>年度考评：</span><span>{{form.examineName}}</span></div>
          </el-col>
          <el-col :span = "6">
            <div><span>考评项目：</span><span>{{form.projectName}}</span></div>
          </el-col>
          <el-col :span = "6">
            <div><span>所属单位：</span><span>{{form.ownDeptName}}</span></div>
          </el-col>
          <el-col :span = "6">
          <div><span>考评对象：</span><span>{{form.ownUserName}}</span></div>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="height: 40px;line-height: 40px;">
          <el-col :span="16" style="text-align: left;font-weight: bold;">
            <div>考评项</div>
          </el-col>
          <el-col :span="2" style="text-align: center;font-weight: bold;">
            <div>分值</div>
          </el-col>
          <el-col :span="6" style="text-align: left;font-weight: bold;">
            <div>考评得分<b style="padding-left: 15px;font-size: 16px; color: red;">{{totalScore}}</b></div>
          </el-col>
        </el-row>
        <el-row :gutter="24" type="flex" v-for="option in form.options" :key="option.optionId" class="mark-content-bottom-border" style="padding-top: 20px;border-bottom: 1px solid #ebebeb;align-items: center;">
          <el-col :span="16" style="text-align: left;">
            <div>{{option.optionName}}</div>
          </el-col>
          <el-col :span="2" style="text-align: center;">
            <div @click="setOptionMaxValue(option)" style="cursor: pointer;">{{option.optionMaxValue}}</div>
          </el-col>
          <el-col :span="6" style="text-align: left;">
            <div style="width: 270px;"><el-input-number size="medium" v-model="option.score" placeholder="评分" :max="option.optionMaxValue" :min="option.optionMinValue" @change="scoreHandle"></el-input-number><el-button type="primary" size="mini" @click="setOptionMaxValue(option)" style="margin-left: 10px;">满分</el-button></div>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
                <el-button @click="resetForm" size="medium" icon="el-icon-close">取消</el-button>
               <el-button v-if="!isView" type="primary"  @click="submit" size="medium" icon="el-icon-check"
                          :loading="loading">保存</el-button>
               <el-button v-if="!isView" type="primary" plain @click="commit" size="medium" icon="el-icon-check"
                          :loading="loading">提交</el-button>
            </span>
    </el-dialog>

    <el-dialog :visible.sync="viewBox" :close-on-click-modal="!viewBox" fullscreen
               :append-to-body="true" :before-close="resetForm" width="1000px" top="5vh">
      <div slot="title">
        <span style="font-size: 20px;margin-right: 20px;">{{formTitle}}</span>
        <el-button @click="resetForm" size="small" type="success" plain>返回</el-button>
      </div>
      <el-form ref="optForm" :model="form" label-width="120px">
        <el-row :gutter="24">
          <el-col :span = "6">
            <div><span>年度考评：</span><span>{{form.examineName}}</span></div>
          </el-col>
          <el-col :span = "6">
            <div><span>考评项目：</span><span>{{form.projectName}}</span></div>
          </el-col>
          <el-col :span = "6">
            <div><span>所属单位：</span><span>{{form.ownDeptName}}</span></div>
          </el-col>
          <el-col :span = "6">
            <div><span>考评对象：</span><span>{{form.ownUserName}}</span></div>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="height: 40px;line-height: 40px;">
          <el-col :span="16" style="text-align: left;font-weight: bold;">
            <div>考评项</div>
          </el-col>
          <el-col :span="2" style="text-align: center;font-weight: bold;">
            <div>分值</div>
          </el-col>
          <el-col :span="6" style="text-align: left;font-weight: bold;">
            <div>考评得分<b style="padding-left: 15px;font-size: 16px; color: red;">{{form.status > 0 ? totalScore : '--'}}</b></div>
          </el-col>
        </el-row>
        <el-row :gutter="24" type="flex" v-for="option in form.options" :key="option.optionId" class="mark-content-bottom-border" style="padding-top: 20px;border-bottom: 1px solid #ebebeb;align-items: center;">
          <el-col :span="16" style="text-align: left;">
            <div>{{option.optionName}}</div>
          </el-col>
          <el-col :span="2" style="text-align: center;">
            <div>{{option.optionMaxValue}}</div>
          </el-col>
          <el-col :span="6" style="text-align: left;">
            <div>{{option.score >= 0 ? option.score : '--'}}</div>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
                <el-button @click="resetForm" size="medium" icon="el-icon-close">取消</el-button>
            </span>
    </el-dialog>

  </basic-container>
</template>

<script>
import {getDetail, getList, remove, statScorePersonTotal, submit} from "@/api/kpi/scorePerson";
import {mapGetters} from "vuex";

export default {
  dictTypes: ['kpi_type'],
  data() {
    return {
      importBox: false,
      isEdit: false,
      isView: false,
      viewBox: false,
      formBox: false,
      formTitle: '',
      loading: true,
      query: {
        year: '',
      },
      form: {},
      page: {
        size: 10,
        current: 1,
        total: 0
      },
      data: [],
      showUploadButton: true,
      fileList: [],
      channels: [],
      editorOption: {
        placeholder: "",
      },
      adminRole:false,
      ownDeptObject: {deptId: ''},
      totalScore: 0,
      scoreTotal: {
        activeTotal: 0,
        scoreTotal: 0,
        total: 0
      }
    }
  },
  computed: {
    ...mapGetters(["userInfo", "permissions"])
  },
  watch: {
    'ownDeptObject.deptId'(val){
      this.query.ownDeptId = val
    }
  },
  created() {
    this.onLoad(this.page);
  },
  methods: {
    getStatScorePersonTotal() {
      statScorePersonTotal(this.query).then((res) => {
        if (res.status === 200 && res.data.data) {
          Object.keys(this.scoreTotal).forEach(item => {
            this.scoreTotal[item] = res.data.data[item] || 0
          })
        }
      })
    },
    scoreHandle() {
      this.totalScore = 0
      this.form.options.forEach(element => {
        if (element.score && Number(element.score) >= 0) {
          this.totalScore += Number(element.score)
        }
      });
    },

    submit(){
      this.performAction(1)
    },
    commit(){
      this.performAction(2)
    },
    performAction(actionStatus) {
      this.$refs['optForm'].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.fileList && this.fileList.map((file) => {
            this.form.thumbUrl = file.response ? file.response.data.url:file.url
          });
          this.form.status = actionStatus
          submit(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.resetForm();
            this.onLoad(this.page);
          }, error => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    showAddView() {
      this.formTitle = '新增';
      this.formBox = true;
    },
    showEditBox(row) {
      getDetail(row.id).then((res) => {
        this.form = res.data.data;
        this.formTitle = '评分';
        this.formBox = true;
        this.isEdit = true;
        this.fileList = [];
        this.fileList.push({url:res.data.data.thumbUrl})
        this.scoreHandle();
      });
    },
    showViewBox(row) {
      getDetail(row.id).then((res) => {
        this.form = res.data.data;
        this.formTitle = '详情';
        this.viewBox = true;
        this.fileList = [];
        this.fileList.push({url:res.data.data.thumbUrl});
        this.scoreHandle();
      });
    },
    handleGenerate(row) {
      this.$confirm("确定一键生成考评评估?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return generate(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return remove(row.id);
      })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    resetForm() {
      this.formBox = false;
      this.isEdit = false;
      this.isView = false;
      this.form = {};
      this.formTitle = '';
      this.$refs['optForm'] && this.$refs['optForm'].resetFields();
      this.viewBox = false;
      this.fileList = [];
      this.auditBox = false;
      this.totalScore = 0;
    },
    onSearch() {
      this.page.current = 1;
      this.onLoad(this.page);
    },
    searchReset() {
      this.query = {
        year: '',
      };
      this.page.current = 1;
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.current = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(current) {
      this.page.current = current;
      this.onLoad(this.page, this.query);
    },
    sizeChange(size) {
      this.page.size = size;
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.current, page.size, Object.assign(params, this.query)).then(res => {
        this.loading = false;
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
      }, error => {
        this.loading = false;
      });
      this.getStatScorePersonTotal();
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
      this.showUploadButton = true
    },
    handleSuccess(response, file, fileList) {
      this.fileList = fileList;
      if (this.fileList.length >= 1) {
        this.showUploadButton = false
      }
    },
    handlePreview(file) {
      window.open(file.url ? file.url : file.response.data.url)
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    setOptionMaxValue(option) {
      option.score = option.optionMaxValue;
      this.scoreHandle()
    }
  }
};
</script>

<style scoped  lang="scss">
.scoreTotal {
  padding-bottom: 10px;
  font-weight: bold;
  font-size: 16px;
  span {
    padding: 0 3px;
    font-size: 20px;
    &:nth-child(1) {
      color: #34ce98;
    }
    &:nth-child(2) {
      color: #ffba01;
    }
    &:nth-child(3) {
      color: #0bcbe5;
    }
  }
}
</style>
